package indi.zhifa.recipe.bailan.framework.common.util;

import cn.hutool.core.io.FileUtil;
import indi.zhifa.recipe.bailan.framework.common.entity.exception.ServiceException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
public class ZfFileMemo {
    private final Map<String,byte[]> fileMemo;
    public ZfFileMemo(){
        fileMemo = new HashMap<>();
    }

    public byte[] loadFile(String pKey, String pFilePath) throws IOException {
        Resource resource = new ClassPathResource(pFilePath);
        File file = resource.getFile();
        byte[] bytes = FileUtil.readBytes(file);
        fileMemo.put(pKey,bytes);
        return bytes;
    }

    public boolean hasKey(String pKey){
        return fileMemo.containsKey(pKey);
    }

    public byte[] getFileContent(String pKey){
        if(!fileMemo.containsKey(pKey)){
            throw new ServiceException("尚未缓存名为"+pKey+"的文件");
        }
        return fileMemo.get(pKey);
    }

    public String getFileString(String pKey){
        byte[] content = getFileContent(pKey);
        return new String(content, StandardCharsets.UTF_8);
    }

}
